const WXAPI = require('apifm-wxapi')
const Base64 = require('base-64')
const CryptoJS = require('crypto-js')

const IMAGE_BASE_URL = 'https://image.randqun.com/'
function imageUtil (originalWidth, originalHeight) {
  let imageSize = {}
  wx.getSystemInfo({
    success: function (res) {
      const windowWidth = res.windowWidth
      imageSize.x = 0
      imageSize.y = 0
      imageSize.windowWidth = windowWidth
      imageSize.imageWidth = originalWidth
      imageSize.imageHeight = originalHeight
      if (originalWidth > windowWidth) {
        imageSize.imageWidth = windowWidth
        imageSize.imageHeight = windowWidth * originalHeight / originalWidth
      } else {
        imageSize.x = (windowWidth - originalWidth) / 2
      }
    }
  })
  return imageSize
}

const upload = async (url)=>{
  const stsRes =  await WXAPI.getSts()
 const formData = getFormDataParams(url,stsRes.data)

 await wx.uploadFile({
    url:"https://image.randqun.com",
    filePath: url,
    name: 'file', // 必须填file。
    formData,
  });

  return {url:IMAGE_BASE_URL + formData.key}
}
const getFormDataParams = (file,credentials) => {

  const date = new Date();
  date.setHours(date.getHours() + 1);
  const policyText = {
      expiration: date.toISOString(), // 设置policy过期时间。
      conditions: [
          // 限制上传大小。
          ["content-length-range", 0, 1024 * 1024 * 1024],
      ],
  };


  const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
  const signature = computeSignature(credentials.accessKeySecret, policy)
  const filePathArr = file.split('/')
  const key =  'group_meal/avatar/' + filePathArr.pop()

  return {
      key,
      policy,
      OSSAccessKeyId: credentials.accessKeyId,
      signature,
      'x-oss-security-token': credentials.securityToken,
      'success_action_status': '200',
  }
}
const computeSignature = (accessKeySecret, canonicalString) =>{

  return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(canonicalString, accessKeySecret));
}
module.exports = {
  imageUtil: imageUtil,
  upload
}
